import { Controller, Sse } from '@nestjs/common';
import { SseService } from './sse.service';
import { Observable } from 'rxjs';
import { exec } from 'child_process';
import { readFileSync } from 'fs';

@Controller('stream')
export class SseController {
  constructor(private readonly sseService: SseService) {}

  @Sse()
  stream() {
    return new Observable((observer) => {
      observer.next({
        data: {
          msg: 'aaa',
        },
      });

      setTimeout(() => {
        observer.next({
          data: {
            msg: 'bbb',
          },
        });
      }, 2000);

      setTimeout(() => {
        observer.next({
          data: {
            msg: 'ccc',
          },
        });
      }, 5000);
    });
  }

  @Sse('sse2')
  stream2() {
    const childProcess = exec('tail -f ./log1');
    return new Observable((observer) => {
      childProcess.stdout.on('data', (msg) => {
        console.log(msg);
        observer.next({ data: { msg: msg.toString() } });
      });
    });
  }

  @Sse('sse3')
  stream3() {
    return new Observable((observer) => {
      let data = readFileSync('./package.json');
      // 假设文件内容是 base64 编码的 JSON 字符串
      const jsonString = data.toString('utf-8'); // 将 Buffer 转换为字符串
      const json = JSON.parse(jsonString); // 解析 JSON
      observer.next({ data: { msg: json } });
    });
  }
}
